let resCache = require('./res/resCache');

globalThis.onload = function () {
    app.start();
};


//--------------------------------
// require
let glExt = require('./glext');
let scene = require('./scene');
let app = {
    resCache:resCache,
    canvas: null,
    gl: null,
    width: -1,
    height: -1,
    lastMs: -1,

    start(){
        scene.loadRes();
        resCache.load(()=>{
            console.log('-----------------------资源加载完毕11.....');
            this.init();
        });
    },

    init() {
        //  let resItem = resCache.getRes('assets/skybox/+x.png')
        // console.log(resItem.data);
        let canvas = document.getElementById('game');
        let width = canvas.width = canvas.clientWidth;
        let height = canvas.height = canvas.clientHeight;
        let gl = canvas.getContext('webgl');
        this.canvas = canvas;
        this.gl = gl;
        this.width = width;
        this.height = height;

        // 使用vao扩展
        glExt.useExt(gl, 'OES_vertex_array_object');
        glExt.useExt(gl, 'ANGLE_instanced_arrays');
        glExt.useExt(gl,'WEBGL_depth_texture');

        this.initGL();

        // TODO:添加各种监听器
        // 添加resize 事件？
        // 添加
        scene.init(this);
        this.lastMs = Date.now();
        this.loop();
    },

    initGL(){
        let gl = this.gl;
        gl.enable(gl.DEPTH_TEST);
        gl.frontFace(gl.CCW);
        gl.cullFace(gl.BACK);
        gl.enable(gl.CULL_FACE);
        gl.clearColor(0,0,0,1);
        gl.viewport(0,0,this.width,this.height);


        // 对纹理坐标进行反转
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,1);

        // 紧密包装数据格式,一次一个
        // TODO:可以进行优化
        gl.pixelStorei(gl.UNPACK_ALIGNMENT,1);
    },

    loop() {
        let now = Date.now();
        let dtMs = now - this.lastMs;
        this.lastMs = now;

        this.frame(dtMs / 1000);
        requestAnimationFrame(this.loop.bind(this));
    },

    frame(dt) {
        // input

        // update
        scene.update(dt);

        // render
        scene.render();
    },
};
globalThis.app = app;

